package com.xh.car.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xh.car.bean.Car;
import com.xh.car.bean.CarImage;
import com.xh.car.mapper.BrandMapper;
import com.xh.car.mapper.CarImageMapper;
import com.xh.car.mapper.CarMapper;
import com.xh.car.service.CarService;
import com.xh.car.util.R;
import com.xh.car.util.RTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author PangJunjie
 * @Date 2024/5/13/013
 */
@Service
@Transactional
public class CarServiceImpl implements CarService {
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CarImageMapper carImageMapper;
    @Autowired
    private BrandMapper brandMapper;

    @Override
    public R getPage(int page, int limit, Car car) {
        PageHelper.startPage(page, limit);
        List<Car> list = carMapper.getAll(car);
        PageInfo<Car> pageInfo = new PageInfo<>(list);
        return R.page(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public void saveOrUpdate(Car car) {
        if (car.getId() == null) {
            Car checkCar = carMapper.checkCarNo(car.getCarNo());
            if (checkCar != null) {
                throw new RTException("车牌号已存在！");
            }
            carMapper.insertSelective(car);
        } else {
            carMapper.updateByPrimaryKeySelective(car);
            carImageMapper.deleteByCarId(car.getId());
        }

        if (car.getCarImages().length > 0) {
            List<CarImage> carImageList = new ArrayList<>();
            for (String ci : car.getCarImages()) {
                CarImage carImage = new CarImage();
                carImage.setCarId(car.getId());
                carImage.setCarImage(ci);
                carImageList.add(carImage);
            }
            carImageMapper.batchInsert(carImageList);
        }
    }

    @Override
    public void deleteById(int id) {
        carMapper.deleteByPrimaryKey(id);
        carImageMapper.deleteByCarId(id);
    }

    @Override
    public Car getById(int id) {
        return carMapper.selectByPrimaryKey(id);
    }

    @Override
    public R getSelect() {
        return R.data(carMapper.getAll(new Car()));
    }

    @Override
    public R getBranList(int pid) {
        return R.data(brandMapper.getListByPid(pid));
    }

    @Override
    public R getCarImage(int id) {
        return R.data(carImageMapper.getListByCarId(id));
    }
}
